package com.nebula.dao;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

/**
 * 连接池
 *
 * @author CcccX
 * @create 2019-01-03 16:10
 */
public class Database {
    
    private static DruidDataSource dataSource;
    private static Connection conn;
    private static PreparedStatement pstmt;
    
    private static ThreadLocal<Connection> threadLocal = new ThreadLocal<>();
    
    static {
        Properties properties = new Properties();
        InputStream inputStream = Database.class.getClassLoader().getResourceAsStream("database.properties");
        try {
            properties.load(inputStream);
            dataSource = (DruidDataSource) DruidDataSourceFactory.createDataSource(properties);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    /**
     * 获得一个连接池
     *
     * @return DruidDataSource
     */
    public static DruidDataSource getDataSource() {
        return dataSource;
    }
    
    public static Connection getConn() {
        try {
            conn = threadLocal.get();
            if (conn == null) {
                conn = dataSource.getConnection();
                threadLocal.set(conn);
            }
            return conn;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }
    
    public static void close() {
        try {
            conn = getConn();
            if (conn != null) {
                conn.close();
                threadLocal.remove();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    
    public static void closeAll(Connection conn, Statement stmt, ResultSet rs) {
        try {
            if (conn != null) {
                conn.close();
            }
            if (stmt != null) {
                stmt.close();
            }
            if (rs != null) {
                rs.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    
    public static Object excute(String sql, Object... objects) {
        boolean flag = false;
        try {
            handle(sql, objects);
            flag = pstmt.execute();
            return flag ? pstmt.getResultSet() : pstmt.getUpdateCount();
        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        }
    }
    
    private static void handle(String sql, Object[] objects) throws SQLException {
        conn = getConn();
        pstmt = conn.prepareStatement(sql);
        if (objects != null) {
            for (int i = 0; i < objects.length; i++) {
                pstmt.setObject(i + 1, objects[i]);
            }
        }
        System.out.println(pstmt);
    }
}
